package com.enation.app.javashop.seller.api.goods;

import com.alibaba.fastjson.JSON;
import com.enation.app.javashop.core.aftersale.model.vo.Result;
import com.enation.app.javashop.core.goods.model.dos.GoodsDO;
import com.enation.app.javashop.core.goods.model.dos.GoodsGalleryDO;
import com.enation.app.javashop.core.goods.model.dto.GoodsDTO;
import com.enation.app.javashop.core.goods.model.dto.GoodsQueryParam;
import com.enation.app.javashop.core.goods.model.dto.UpdateShopCatDTO;
import com.enation.app.javashop.core.goods.model.enums.Permission;
import com.enation.app.javashop.core.goods.model.vo.*;
import com.enation.app.javashop.core.goods.service.GoodsGalleryManager;
import com.enation.app.javashop.core.goods.service.GoodsManager;
import com.enation.app.javashop.core.goods.service.GoodsQueryManager;
import com.enation.app.javashop.core.promotion.shetuan.service.ShetuanGoodsOperateManager;
import com.enation.app.javashop.core.shop.model.vo.ShopCatItem;
import com.enation.app.javashop.core.shop.service.ShopCatManager;
import com.enation.app.javashop.framework.context.UserContext;
import com.enation.app.javashop.framework.database.Page;
import com.enation.app.javashop.framework.exception.ServiceException;
import com.enation.app.javashop.framework.security.model.Seller;
import com.enation.app.javashop.framework.util.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.beanutils.ConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 商品控制器
 *
 * @author fk
 * @version v2.0
 * @since v7.0.0 2018-03-21 11:23:10
 */
@RestController
@RequestMapping("/seller/goods")
@Api(description = "商品相关API")
@Validated
@Scope("request")
public class GoodsSellerController {

	@Autowired
	private GoodsQueryManager goodsQueryManager;

	@Autowired
	private GoodsManager goodsManager;

	@Autowired
	private ShetuanGoodsOperateManager shetuanGoodsOperateManager;

	@Autowired
	private ShopCatManager shopCatManager;

	@Autowired
	private GoodsGalleryManager goodsGalleryManager;

	@ApiOperation(value = "查询商品列表", response = GoodsDO.class)
	@GetMapping
	public Page list(GoodsQueryParam param,@ApiIgnore Integer pageNo, @ApiIgnore Integer pageSize) {

		param.setPageNo(pageNo);
		param.setPageSize(pageSize);

		Seller seller = UserContext.getSeller();
		param.setSellerId(seller.getSellerId());

		Page page = this.goodsQueryManager.list(param);

		List<Map> data = page.getData();
		if (!CollectionUtils.isEmpty(data)) {
			List<Integer> goodsIdList = new ArrayList<>();
			for (Map good : data) {
				// 商品ID
				goodsIdList.add((Integer) good.get("goods_id"));
                good.put("shop_cat_item_list",JSON.parseArray((String) good.get("shop_cat_items"), ShopCatItem.class));
			}
			Map<Integer, List<GoodsGalleryDO>> goodsGallersMap = goodsGalleryManager.getGoodsGallersByGoodsIds(goodsIdList.toArray(new Integer[goodsIdList.size()]));
			if (goodsGallersMap != null) {
				for (Map good : data) {
					good.put("goods_gallery_list", goodsGallersMap.get((Integer) good.get("goods_id")));
				}
			}

		}

		return page;
	}

	@ApiOperation(value = "查询预警商品列表", response = GoodsDO.class)
	@ApiImplicitParams({
		@ApiImplicitParam(name = "page_no", value = "页码", required = false, dataType = "int", paramType = "query"),
		@ApiImplicitParam(name = "page_size", value = "每页数量", required = false, dataType = "int", paramType = "query"),
		@ApiImplicitParam(name = "keyword", value = "查询关键字", required = false, dataType = "string", paramType = "query")
	})
	@GetMapping("/warning")
	public Page warningList(@ApiIgnore Integer pageNo,@ApiIgnore Integer pageSize,String keyword){

		return this.goodsQueryManager.warningGoodsList(pageNo,pageSize,keyword);

	}


	@ApiOperation(value = "添加商品", response = GoodsDO.class)
	@ApiImplicitParam(name = "goods", value = "商品信息", required = true, dataType = "GoodsDTO", paramType = "body")
	@PostMapping
	public GoodsDO add(@ApiIgnore @Valid @RequestBody GoodsDTO goods) {

		GoodsDO  goodsDO = this.goodsManager.add(goods);

		return goodsDO;
	}

	@PutMapping(value = "/{id}")
	@ApiOperation(value = "修改商品", response = GoodsDO.class)
	@ApiImplicitParams({
		@ApiImplicitParam(name = "id", value = "主键", required = true, dataType = "int", paramType = "path"),
		@ApiImplicitParam(name = "goods", value = "商品信息", required = true, dataType = "GoodsDTO", paramType = "body")
	})
	public GoodsDO edit(@Valid @RequestBody GoodsDTO goods, @PathVariable Integer id) {
		GoodsDO goodsDO = this.goodsManager.edit(goods, id);

		return goodsDO;
	}

	@GetMapping(value = "/{id}")
	@ApiOperation(value = "查询一个商品,商家编辑时使用")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id", value = "要查询的商品主键", required = true, dataType = "int", paramType = "path") })
	public GoodsVO get(@PathVariable Integer id) {

		GoodsVO goods = this.goodsQueryManager.sellerQueryGoods(id);

		return goods;
	}

	@ApiOperation(value = "商家下架商品",notes = "商家下架商品时使用")
	@ApiImplicitParams({
		@ApiImplicitParam(name="goods_ids",value="商品ID集合",required=true,paramType="path",dataType="int",allowMultiple=true)
	})
	@PutMapping(value = "/{goods_ids}/under")
	public String underGoods(@PathVariable("goods_ids") Integer[] goodsIds,String reason){
		if(StringUtil.isEmpty(reason)){
			reason = "自行下架，无原因";
		}
		this.goodsManager.under(goodsIds,reason,Permission.SELLER);

		return null;
	}

	@ApiOperation(value = "商家将商品放入回收站",notes = "下架的商品才能放入回收站")
	@ApiImplicitParams({
		@ApiImplicitParam(name="goods_ids",value="商品ID集合",required=true,paramType="path",dataType="int",allowMultiple=true)
	})
	@PutMapping(value = "/{goods_ids}/recycle")
	public String deleteGoods(@PathVariable("goods_ids") Integer[] goodsIds){

		this.goodsManager.inRecycle(goodsIds);

		return null;
	}

    @ApiOperation(value = "更新商品多分组", notes = "更新商品多分组")
    @PostMapping(value = "/updateMultiShopCat")
    public List<ShopCatItem> updateMultiShopCat(@RequestBody UpdateShopCatDTO updateShopCatDTO) {
        Integer goodsId = updateShopCatDTO.getGoodsId();
        List<ShopCatItem> shopCatItems = this.shopCatManager.getByIds(updateShopCatDTO.getShopCatIds());
        this.goodsManager.updateGoodsShopCat(goodsId, shopCatItems);
        this.shetuanGoodsOperateManager.updateGoodsCat(goodsId, shopCatItems);
        return shopCatItems;
    }

    @ApiOperation(value = "批量更新商品多分组", notes = "批量更新商品多分组")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "shop_cat_ids", value = "分类ID", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "goods_ids", value = "商品ID", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "update_type", value = "修改商品类型,1-社团商品，0-普通商品", required = true, dataType = "int", paramType = "query")
	})
    @PostMapping(value = "/batchUpdateMultiShopCat")
    public Result batchUpdateMultiShopCat(@ApiIgnore String shopCatIds,@ApiIgnore String goodsIds,@ApiIgnore Integer updateType) {
         if (StringUtil.isEmpty(shopCatIds)||updateType==null||StringUtil.isEmpty(goodsIds)) {
            return new Result(500, "批量修改商品多分组参数错误", null);
        }
        String[] goodsIdArray=goodsIds.split(",");
		String[] shopCatIdAyyay=shopCatIds.split(",");
		Integer[] newids = (Integer[]) ConvertUtils.convert(shopCatIdAyyay,Integer.class);
        for (String goodsIdString : goodsIdArray) {
            Integer goodsId = Integer.parseInt(goodsIdString);
            List<ShopCatItem> shopCatItems = this.shopCatManager.getByIds(Arrays.asList(newids));
            this.goodsManager.updateGoodsShopCat(goodsId, shopCatItems);
            // 如果修改的是社团商品才需要调这个接口
            if (updateType == 1) {
                this.shetuanGoodsOperateManager.updateGoodsCat(goodsId, shopCatItems);
            }
        }
        return Result.successMessage();
    }

	@ApiOperation(value = "商家还原商品",notes = "商家回收站回收商品时使用")
	@ApiImplicitParams({
		@ApiImplicitParam(name="goods_ids",value="商品ID集合",required=true,paramType="path",dataType="int",allowMultiple=true)
	})
	@PutMapping(value="/{goods_ids}/revert")
	public String revertGoods(@PathVariable("goods_ids") Integer[] goodsIds){

		this.goodsManager.revert(goodsIds);

		return null;
	}

	@ApiOperation(value = "商家彻底删除商品",notes = "商家回收站删除商品时使用")
	@ApiImplicitParams({
		@ApiImplicitParam(name="goods_ids",value="商品ID集合",required=true,paramType="path",dataType="int",allowMultiple=true)
	})
	@DeleteMapping(value="/{goods_ids}")
	public String cleanGoods(@PathVariable("goods_ids") Integer[] goodsIds){

		this.goodsManager.delete(goodsIds);

		return "";
	}


	@GetMapping(value = "/{goods_ids}/details")
	@ApiOperation(value = "查询多个商品的基本信息")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "goods_ids", value = "要查询的商品主键", required = true, dataType = "int", paramType = "path",allowMultiple = true) })
	public List<GoodsSelectLine> getGoodsDetail(@PathVariable("goods_ids") Integer[] goodsIds) {

		Seller seller = UserContext.getSeller();

		return this.goodsQueryManager.query(goodsIds,seller.getSellerId());
	}


	/**
	 * @author john
	 * @since   2020-5-14
	 * 批量将商品上架
	 */
	@PutMapping(value = "/{goods_ids}/ups")
	@ApiOperation(value = "商家批量上架",notes = "商家批量上架")
	@ApiImplicitParams({
			@ApiImplicitParam(name="goods_ids",value="商品ID集合",required=true,paramType="path",dataType="int",allowMultiple=true)
	})
	public String ups(@PathVariable("goods_ids") Integer[] goodsIds){
		Seller seller = UserContext.getSeller();
		if(goodsIds==null || goodsIds.length<1){
			return "请选择商品";
		}
		this.goodsManager.ups(seller.getSellerId() , goodsIds);
		return  "";
	}

	@PostMapping(value = "/copyGoods")
	@ApiOperation(value = "复制商品")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "goodsIds", value = "要复制的商品主键", required = true, dataType = "string", allowMultiple = true)})
	public CopyGoodsResult copyGoods(@RequestParam(value = "goodsIds")String goodsIds){
		return this.goodsManager.copyGoods(goodsIds,UserContext.getSeller().getSellerId());
	}

}
